import 'package:flutter/material.dart';
import '../../utils/Global.dart';
import 'package:provider/provider.dart';
import '../../provider/UserProvider.dart';
import 'package:url_launcher/url_launcher.dart';
class Pay extends StatefulWidget {
  final int id;
  final String title;
  Pay({Key? key, required this.id, required this.title}): super(key: key);
  @override
  State<Pay> createState() => _PayState(id);
}

class _PayState extends State<Pay> {
  int detailId = 0;
  int payType = 2;
  
  _PayState(int id) {
    detailId = id;
  }
  String pic = "http://192.168.2.135:3000/3.jpg";
  @override
  void initState() {
    // print('$widget, 打印组件内容');
    // G.api.course.courseDetail(id: widget.id).then((dynamic value) {
       
    //   setState(() {
    //     for(int i = 0; i < value.length; i++) {
    //       if(value[i]['id']  == detailId) {
    //         course = value[i]!;
            
    //         break;
    //       }
    //     }
    //   });
    // });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('支付'),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future: G.api.course.courseDetail(id: widget.id),
        builder: (context, snapshot) {
          switch(snapshot.connectionState) {
            case ConnectionState.none:
               return Container(child: Text(''));
            case ConnectionState.waiting: // 正在等待
              return Center(
                child: CircularProgressIndicator()
              );
            case ConnectionState.done:
             if(snapshot.hasError) {
              return Center(
                child: Text('${snapshot.error}',
                style: TextStyle(color: Colors.red)),
              );
             } else if (snapshot.hasData) {
              var value = snapshot.data;
              Map<String?, dynamic> course = {
                'courseName': '',
                'courseImgUrl': '',
                'sales': '',
                'price': '',
                'oldPrice': '',
                'teacherDTO': {
                  'teacherName': ''
                }
              };
              for(int i = 0; i < value.length; i++) {
                if(value[i]['id']  == detailId) {
                  course = value[i]!;
                  break;
                }
              }
              return SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ListTile(
                      title: Text(
                        course['courseName'],
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w500
                        ),
                      ),
                      subtitle: course['discounts'] != null ? Text(
                        '¥' + course['discounts'].toString(),
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w500,
                          color: Colors.red
                        ),
                      ) : Text(''),
                      leading: course['courseListImg'] != null ?  Image.network(
                        course['courseListImg'],
                        fit: BoxFit.cover,
                        height: 200,
                    ) : Icon(Icons.hourglass_empty_outlined)
                    ),
                    Container(
                      margin: EdgeInsets.all(12),
                      child: Text('当前用户：' + userProvider.userInfo['username'] ?? ''),
                    ),
                    Container(
                      margin: EdgeInsets.all(12),
                      child: Text(
                        '支付方式',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500
                        ),
                      ),
                    ),
                    Divider(),
                    RadioListTile(
                      value: 1, 
                      groupValue: this.payType, 
                      onChanged: (val) {
                        setState(() {
                          payType = val!;
                        });
                      },
                      title: Text('微信支付'),
                      secondary: Image.network(
                        "http://www.lgstatic.com/lg-app-fed/pay/images/wechat_b787e2f4.png",
                        width: 30,
                        fit: BoxFit.cover
                      ),
                      selected: payType == 1,
                      selectedTileColor: Colors.green[100],
                      // contentPadding: EdgeInsets.all(10), // 间距
                    ),
                    RadioListTile(
                      value: 2, 
                      groupValue: this.payType, 
                      onChanged: (val) {
                        setState(() {
                          payType = val!;
                        });
                        
                      },
                      title: Text('支付宝'),
                      secondary: Image.network(
                        "http://www.lgstatic.com/lg-app-fed/pay/images/ali_ed78fdae.png",
                        width: 30,
                        fit: BoxFit.cover
                      ),
                      selected: payType == 2,
                      selectedTileColor: Colors.green[100],
                    ),
                    Container(
                      margin: EdgeInsets.all(20),
                      width: double.infinity,
                      child: ElevatedButton(
                        child: Text('立即支付'),
                        onPressed: () {

                        },
                        style: ButtonStyle(
                          // background: Colors.blue,
                          textStyle: MaterialStateProperty.all(
                            const TextStyle(
                              fontSize: 14,
                              
                            )
                          )
                        ),
                      ),
                    )
                ]),
              );
             } else {
                return Center(
                  child: CircularProgressIndicator()
                );
              }
            // case ConnectionState.active:
              // TODO: Handle this case.
            default:  return Container(child: Text(''));
          }
        },
      )
      
    );
  }

  doPay() {
    // 发起支付
    G.api.user.createPay(orderNo: 'orderNo', channel: 55).then((value) {
      if (value != false) {
        print('支付成功');
        print(value);
        /// 跳转到支付链接
        _launchURL(value['payUrl']);
      } else {
        print('支付失败');
      }
    });
  }

  void _launchURL(_url) async => 
    // ignore: deprecated_member_use
    await canLaunch(_url) 
    ? 
    // ignore: deprecated_member_use
    await launch(_url) 
    : 
    throw '不能跳转到 $_url';


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}